﻿#include "ZFileLoggerPrivate.h"

ZFileLoggerPrivate::ZFileLoggerPrivate(const QString &file_path)
    : m_new_line_symbol("\n"),
      m_log_filepath(file_path),
      m_log_file(file_path)
{
    open();
}

ZFileLoggerPrivate::~ZFileLoggerPrivate()
{

}

ZFileLoggerPrivate &ZFileLoggerPrivate::operator<<(const QString &msg)
{
    m_mutex.lock();
    m_out_stream << msg << m_new_line_symbol;
    m_mutex.unlock();

    return *this;
}

ZFileLoggerPrivate &ZFileLoggerPrivate::operator<<(const QStringList &msgs)
{
    QString msg = msgs.join(m_new_line_symbol).append(m_new_line_symbol);
    m_mutex.lock();
    m_out_stream << msg;
    m_mutex.unlock();

    return *this;
}

void ZFileLoggerPrivate::setNewLineSymbol(const QString &symbol)
{
    m_new_line_symbol = symbol;
}

QString ZFileLoggerPrivate::getLastErrorString()
{
    return m_last_error_string;
}

bool ZFileLoggerPrivate::open()
{
    if (!m_log_file.open(QIODevice::Append))
    {
        QString error_string = QObject::tr("Can't not open log file %1! Error Reason: %2.")
                .arg(m_log_filepath)
                .arg(m_log_file.errorString());
        m_last_error_string = error_string;
        return false;
    }

    m_out_stream.setDevice(&m_log_file);
    return true;
}

void ZFileLoggerPrivate::close()
{
    m_out_stream.flush();
    m_log_file.close();
}


